#include "../net/SockLite.h"
#include "../include/mystdafx.h"

CSockLite::CSockLite(void)
{
	m_hSocket = OS_INVALID_SOCKET;
}

CSockLite::~CSockLite(void)
{
}

bool CSockLite::Create()
{
	if( m_hSocket == OS_INVALID_SOCKET )
	{
		os_tcpsock_open(&m_hSocket, 0);
	}
	return OS_INVALID_SOCKET != m_hSocket;
}

void CSockLite::Attach( os_socket_t hSocket )
{
	assert( OS_INVALID_SOCKET != hSocket );

	Close();

	m_hSocket = hSocket;
}

void CSockLite::Close()
{
	if( OS_INVALID_SOCKET == m_hSocket )
		return;

	os_tcpsock_close(&m_hSocket);
	m_hSocket = OS_INVALID_SOCKET;
}

bool CSockLite::Connect( const char* lpszHostAddress, UINT nHostPort )
{
	assert( lpszHostAddress != NULL );

	if( NULL == lpszHostAddress )
		return false;

	os_sockaddr_t sockAddr;
	memset( &sockAddr, 0, sizeof(sockAddr) );

	sockAddr.iAddr.sin_family = AF_INET;
	sockAddr.iAddr.sin_addr.s_addr = inet_addr(lpszHostAddress);
	sockAddr.iAddr.sin_port = htons((unsigned short)nHostPort);

	return -1 != os_tcpsock_connect(m_hSocket, &sockAddr);
}

// Attributes

os_socket_t CSockLite::GetSocket() const
{
	return m_hSocket;
}

bool CSockLite::GetPeerName( std::string& rPeerAddress, UINT& rPeerPort )
{
	os_sockaddr_t sockAddr;
	memset(&sockAddr, 0, sizeof(sockAddr));

	if(os_sock_getpeeraddr(m_hSocket, &sockAddr) == OS_SOCKET_ERROR)
		return false;

	rPeerPort = ntohs(sockAddr.iAddr.sin_port);
	rPeerAddress = ::inet_ntoa(sockAddr.iAddr.sin_addr);

	return true;
}

bool CSockLite::GetSockName( std::string& rSocketAddress, UINT& rSocketPort )
{
	os_sockaddr_t sockAddr;
	memset(&sockAddr, 0, sizeof(sockAddr));

	os_sockaddr_t addr;

	if( !os_sock_getlocaladdr(m_hSocket, &addr) )
		return false;

	rSocketPort = ntohs(sockAddr.iAddr.sin_port);
	rSocketAddress = ::inet_ntoa(sockAddr.iAddr.sin_addr);
	
	return true;
}

bool CSockLite::IOCtl( long command, DWORD* args)
{
	if(socket_ioctl(m_hSocket, command, (DWORD*)&args) < 0)
		return false;
	return true;
}

int CSockLite::Receive( void* lpBuf, int nBufLen, int nFlags )
{
	return os_tcpsock_recv(m_hSocket, (char*)lpBuf, nBufLen, nFlags);
}

int CSockLite::Send( const void* lpBuf, int nBufLen, int nFlags )
{
	return os_tcpsock_send(m_hSocket, (char*)lpBuf, nBufLen, nFlags);
}

bool CSockLite::HasError()
{
#ifdef WIN32  
	int err = WSAGetLastError();  
	if(err != WSAEWOULDBLOCK) {  
#else  
	int err = errno;  
	if(err != EINPROGRESS && err != EAGAIN) {  
#endif  
		return true;  
	}  

	return false;  
}